﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using User.Api.Dto.sfkd;
using User.Api.HttpClients;
using System.Net.Http;
using System.Web.Http;
using User.Api.Helpers;
using Common.Logging;
using OutDbContext;
using System.Threading;
using System.Web.Http.Controllers;
using MySql.Data.MySqlClient;

namespace User.Api.Controllers
{
    public class SFKDController : ApiController
    {
        private static readonly string setAppId = "00023655";
        private static readonly string setAppKey = "129A43A3C58088458A88D208384DED36";
        private static readonly ILog Logger = LogManager.GetLogger(typeof(BillOrderController));

        private static readonly object OrderNoLocker = new object();
        private GdsfybjyWeiXinEntities _ctx;
        protected override void Initialize(HttpControllerContext controllerContext)
        {
            _ctx = new GdsfybjyWeiXinEntities();
            base.Initialize(controllerContext);
        }

        protected override void Dispose(bool disposing)
        {
            _ctx.Dispose();
            base.Dispose(disposing);
        }
        /// <summary>
        /// 申请令牌
        /// </summary>
        /// <returns></returns>
        public MessageResp<LinPaiRespDto> linPai()
        {
            var date = DateTime.Now.ToString("yyyy-MM-dd");
            var linPaiOrder = _ctx.SFKDLinPais.FirstOrDefault(x => x.Date == date);
           
            var respHQ = new MessageResp<LinPaiRespDto>();
            var respDto = new LinPaiRespDto();
            if (linPaiOrder != null)
            {
                respDto.accessToken = linPaiOrder.accessToken;
                respDto.refreshToken = linPaiOrder.refreshToken;
                respHQ.body = respDto;
                return respHQ;
            }
            
            var newSFOrderNo = SFKDNewOrderNo();
            String url = "/public/v1.0/security/access_token/sf_appid/" + setAppId + "/ sf_appkey/" + setAppKey;
            MessageReq<LinPaiReqDto> req = new MessageReq<LinPaiReqDto>();
            HeadMessageReq reqHQ = new HeadMessageReq
            {
                transType = "301",
                transMessageId = newSFOrderNo
            };
            req.head = reqHQ;
            LinPaiReqDto linPaiHQ = new LinPaiReqDto
            {

            };
            req.body = linPaiHQ;
            
            try
            {
                var httpClient = sfkd.GetClient();
                var responseMsg = httpClient.PostAsJsonAsync(url, req).Result;
                responseMsg.EnsureSuccessStatusCode();
                respHQ = responseMsg.Content.ReadAsAsync<MessageResp<LinPaiRespDto>>().Result;
                //response = responseMsg.Content.ReadAsAsync<MessageResp<OrderReqDto>>().Result;
            }
            catch (Exception ex)
            {
                //Logger.ErrorFormat("调用院内获取病人信息Api出错,信息：{0}", JsonConvert.SerializeObject(ex));
                //return new AddBindingResponse
                //{
                //    ResultCode = "3",
                //    ResultMsg = "操作失败，获取就诊卡信息超时"
                //};
            }

            var order = new SFKDLinPai
            {
                accessToken = respHQ.body.accessToken,
                refreshToken = respHQ.body.refreshToken,
                CreateTime = DateTime.Now,
                UpdateTime = DateTime.Now,
            Date = date
            };
            _ctx.SFKDLinPais.Add(order);
            _ctx.SaveChanges();

            return respHQ;
        }
        /// <summary>
        /// 更新令牌
        /// </summary>
        /// <returns></returns>
        public MessageResp<LinPaiRespDto> newLinPai()
        {
            var date = DateTime.Now.ToString("yyyy-MM-dd");
            var linPaiOrder = _ctx.SFKDLinPais.FirstOrDefault(x => x.Date == date);

            var respHQ = new MessageResp<LinPaiRespDto>();
            var respDto = new LinPaiRespDto();

            var newSFOrderNo = SFKDNewOrderNo();
            String url = "/public/v1.0/security/refresh_token/access_token/"+linPaiOrder.accessToken + "/refresh_token/"+ linPaiOrder.refreshToken+"/sf_appid/" + setAppId + "/ sf_appkey/" + setAppKey;
            MessageReq<LinPaiReqDto> req = new MessageReq<LinPaiReqDto>();
            HeadMessageReq reqHQ = new HeadMessageReq
            {
                transType = "302",
                transMessageId = newSFOrderNo
            };
            req.head = reqHQ;
            LinPaiReqDto linPaiHQ = new LinPaiReqDto
            {

            };
            req.body = linPaiHQ;

            try
            {
                var httpClient = sfkd.GetClient();
                var responseMsg = httpClient.PostAsJsonAsync(url, req).Result;
                responseMsg.EnsureSuccessStatusCode();
                respHQ = responseMsg.Content.ReadAsAsync<MessageResp<LinPaiRespDto>>().Result;
                //response = responseMsg.Content.ReadAsAsync<MessageResp<OrderReqDto>>().Result;
            }
            catch (Exception ex)
            {
                //Logger.ErrorFormat("调用院内获取病人信息Api出错,信息：{0}", JsonConvert.SerializeObject(ex));
                //return new AddBindingResponse
                //{
                //    ResultCode = "3",
                //    ResultMsg = "操作失败，获取就诊卡信息超时"
                //};
            }

            linPaiOrder.accessToken = respHQ.body.accessToken;
            linPaiOrder.refreshToken = respHQ.body.refreshToken;
            linPaiOrder.UpdateTime = DateTime.Now;
            _ctx.SaveChanges();

            return respHQ;
        }


        /// <summary>
        /// 下单
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [ActionName("testOrder")]
        [AllowAnonymous]
        public testOrder testOrder(int orderId)
        {
            var azUser = AzUser.GetInApi(Request);
            var card = _ctx.Addresses.FirstOrDefault(x => x.IsDefault == 1 && x.WxUserId == azUser.UserId);
            if (card == null)
            {
                return new testOrder
                {
                    ResultCode = "1",
                    ResultMsg = "找不到就诊卡信息"
                };
            }
            var bill = _ctx.BillOrders.FirstOrDefault(x => x.Id == orderId);

            if (bill == null)
            {
                return new testOrder
                {
                    ResultCode = "1",
                    ResultMsg = "找不到缴费信息"
                };
            }
            var sfkdOrder = _ctx.SFKDorders.FirstOrDefault(x => x.OrderNo == bill.OrderNo && x.OrderStatus == 1);
            if(sfkdOrder!=null)
            {
                return new testOrder
                {
                    ResultCode = "1",
                    ResultMsg = "请勿重复下单！"
                };
            }
            MessageResp<OrderRespDto> response = new MessageResp<OrderRespDto>();
            MessageResp<LinPaiRespDto> linPaiResp = linPai();
            
            if (linPaiResp.body.accessToken == "")
            {
                return new testOrder
                {
                    ResultCode = "1",
                    ResultMsg = "申请令牌出错"
                };
            }
            string urlOrder = "/rest/v1.0/order/access_token/" + linPaiResp.body.accessToken + "/sf_appid/" + setAppId + "/sf_appkey/" + setAppKey;
            MessageReq<OrderReqDto> reqOrder = new MessageReq<OrderReqDto>();
            var newSFOrderNo = SFKDNewOrderNo();
            HeadMessageReq reqXD = new HeadMessageReq
            {
                transType = "200",
                transMessageId = newSFOrderNo
            };
            reqOrder.head = reqXD;

            var newOrderNo = GenerateNewOrderNo();

            DateTime data = DateTime.Now;
            string sendStartTime = "";
            if (data.Hour<11)
            {
                sendStartTime = DateTime.Now.ToString("yyyy-MM-dd") + " 12:00:00";
            }
            else
            {
                sendStartTime = DateTime.Now.ToString("yyyy-MM-dd") + " 18:00:00";
            }
            OrderReqDto dto = new OrderReqDto
            {
                orderId = newOrderNo,
                expressType = "1",
                payMethod = 2,
                isDoCall = 1,
                isGenBillno = 1,
                isGenEletricPic = 0,
                custId = "7550010173",
                // payArea = "7552732",
                sendStartTime = sendStartTime,
               // needReturnTrackingNo = "0",
                remark = "易碎物品，小心轻放"
            };
            DeliverConsigneeInfoDto dto2 = new DeliverConsigneeInfoDto
            {
                company = "个人",
                contact = card.CardName,
                tel = card.Phone,
                province = card.Province,
                city = card.City,
                county = card.County,
                address = card.Address1
                //shipperCode = "787564",
                //mobile = "13612822894"
            };
            //DeliverConsigneeInfoDto dto3 = new DeliverConsigneeInfoDto
            //{
            //    address = "世界第一广场",
            //    city = "深圳",
            //    company = "顺丰",
            //    contact = "张三",
            //    county = "中国",
            //    province = "广东",
            //    shipperCode = "518100",
            //    tel = "0755-33915561",
            //    mobile = "18588413321"
            //};
            CargoInfoDto dto4 = new CargoInfoDto
            {
                parcelQuantity = 1,
                cargo = "药品配送"
                //cargoCount = "1000",
                //cargoUnit = "部",
                //cargoWeight = "12",
                //cargoAmount = "5200"
                //cargoTotalWeight = 0.8
            };
            //List<AddedServiceDto> list = new List<AddedServiceDto>();
            //AddedServiceDto item = new AddedServiceDto
            //{
            //    name = "COD",
            //    value = "20000"
            //};
            //list.Add(item);
            //AddedServiceDto dto6 = new AddedServiceDto
            //{
            //    name = "CUSTID",
            //    value = "7552732920"
            //};
            //list.Add(dto6);
            //dto.deliverInfo = dto2;
            dto.consigneeInfo = dto2;
            dto.cargoInfo = dto4;
            //dto.addedServices = list;
            reqOrder.body = dto;

            var order = new SFKDorder
            {
                WxUserId = azUser.UserId,
                CardNo = bill.CardNo,
                CardName = card.CardName,
                Phone = card.Phone,
                Province = card.Province,
                City = card.City,
                County = card.County,
                Address = card.Address1,
                ClinicNo = bill.ClinicNo,
                OrderNo = bill.OrderNo,
                OrderId = dto.orderId,
                CustId = dto.custId,
                CreateTime = DateTime.Now,
                SendStartTime=dto.sendStartTime.ToDateTime(),
                OrderStatus=0,
            };
            _ctx.SFKDorders.Add(order);
            _ctx.SaveChanges();

            try
            {
                var httpClient = sfkd.GetClient();
                var responseMsg = httpClient.PostAsJsonAsync(urlOrder, reqOrder).Result;
                responseMsg.EnsureSuccessStatusCode();
                response = responseMsg.Content.ReadAsAsync<MessageResp<OrderRespDto>>().Result;
            }
            catch (Exception ex)
            {
                //Logger.ErrorFormat("调用快速下单接口出错,信息：{0}", JsonConvert.SerializeObject(ex));

                //MessageResp<OrderQueryRespDto> t=SFKDController.SFKDNewOrderNo
                //return new AddBindingResponse
                //{
                //    ResultCode = "3",
                //    ResultMsg = "操作失败，获取就诊卡信息超时"
                //};
            }
            if (response.head.code == "EX_CODE_OPENAPI_0105" || response.head.code == "EX_CODE_OPENAPI_0106")
            {
                MessageResp<LinPaiRespDto> newLinPaiResp = newLinPai();
                testOrder newOrder = testOrder(orderId);
                return newOrder;
            }
            if (response.head.code != "EX_CODE_OPENAPI_0200")
            {
                return new testOrder
                {
                    ResultCode = "1",
                    ResultMsg = response.head.message
                };
            }

            order.OrderStatus = 1;
            _ctx.SaveChanges();

            return new testOrder
            {
                ResultCode = "0",
                ResultMsg = response.head.message,
                OrderId= response.body.orderId
            };
        }

        /// <summary>
        /// 订单筛选
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [ActionName("testFilterOrder")]
        [AllowAnonymous]
        public MessageResp<OrderFilterRespDto> testFilterOrder()
        {

            MessageResp<OrderFilterRespDto> respDto = new MessageResp<OrderFilterRespDto>();

            AppInfo appInfo = new AppInfo();
            appInfo.setAppId = ("00023655");
            appInfo.setAppKey = ("129A43A3C58088458A88D208384DED36");
            String url = "/public/v1.0/security/access_token/sf_appid/" + appInfo.setAppId + "/ sf_appkey/" + appInfo.setAppKey;
            MessageReq<LinPaiReqDto> req = new MessageReq<LinPaiReqDto>();
            HeadMessageReq reqHQ = new HeadMessageReq
            {
                transType = "301",
                transMessageId = "11111111111222"
            };
            req.head = reqHQ;
            LinPaiReqDto linPaiHQ = new LinPaiReqDto
            {

            };
            req.body = linPaiHQ;
            MessageResp<LinPaiRespDto> respHQ = new MessageResp<LinPaiRespDto>();
            try
            {
                var httpClient = sfkd.GetClient();
                var responseMsg = httpClient.PostAsJsonAsync(url, req).Result;
                responseMsg.EnsureSuccessStatusCode();
                respHQ = responseMsg.Content.ReadAsAsync<MessageResp<LinPaiRespDto>>().Result;
                //response = responseMsg.Content.ReadAsAsync<MessageResp<OrderReqDto>>().Result;
            }
            catch (Exception ex)
            {
                //Logger.ErrorFormat("调用院内获取病人信息Api出错,信息：{0}", JsonConvert.SerializeObject(ex));
                //return new AddBindingResponse
                //{
                //    ResultCode = "3",
                //    ResultMsg = "操作失败，获取就诊卡信息超时"
                //};
            }
            if (respHQ.head.code != "EX_CODE_OPENAPI_0200")
            {
                respDto.head.message = respHQ.head.code;
                return respDto;
            }

            string urlFilter = "/rest/v1.0/filter/access_token/" + respHQ.body.accessToken + "/sf_appid/" + appInfo.setAppId + "/sf_appkey/" + appInfo.setAppKey;
            MessageReq<OrderFilterReqDto> reqFilter = new MessageReq<OrderFilterReqDto>();
            HeadMessageReq reqXD = new HeadMessageReq
            {
                transType = "204",
                transMessageId = "111111145624223588"
            };
            reqFilter.head = reqXD;
            OrderFilterReqDto dtoXD = new OrderFilterReqDto
            {
                filterType = 1,
                consigneeCountry = "中国",
                consigneeProvince = "广东省",
                consigneeCity = "深圳市",
                consigneeCounty = "南山区",
                consigneeAddress = "南海大道3688号",
                consigneeTel = "26536114",
                deliverCountry = "中国",
                deliverProvince = "湖北省",
                deliverCity = "武汉市",
                deliverCounty = "武昌区",
                deliverAddress = "八一路299号",
                deliverTel = "74512587"
            };
            reqFilter.body = dtoXD;
            try
            {
                var httpClient = sfkd.GetClient();
                var responseMsg = httpClient.PostAsJsonAsync(urlFilter, reqFilter).Result;
                responseMsg.EnsureSuccessStatusCode();
                respDto = responseMsg.Content.ReadAsAsync<MessageResp<OrderFilterRespDto>>().Result;
                //response = responseMsg.Content.ReadAsAsync<MessageResp<OrderReqDto>>().Result;
            }
            catch (Exception ex)
            {
                //Logger.ErrorFormat("调用院内获取病人信息Api出错,信息：{0}", JsonConvert.SerializeObject(ex));
                //return new AddBindingResponse
                //{
                //    ResultCode = "3",
                //    ResultMsg = "操作失败，获取就诊卡信息超时"
                //};
            }
            if (respDto.head.code != "EX_CODE_OPENAPI_0200" && respDto.head.message == "操作成功")
            {
                return respDto;
            }

            return respDto;
        }

        /// <summary>
        /// 订单结果查询
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [ActionName("testOrderQuery")]
        [AllowAnonymous]
        public MessageResp<OrderQueryRespDto> testOrderQuery()
        {
            MessageResp<OrderQueryRespDto> respQuery = new MessageResp<OrderQueryRespDto>();
            AppInfo appInfo = new AppInfo();
            appInfo.setAppId = ("00023655");
            appInfo.setAppKey = ("129A43A3C58088458A88D208384DED36");
            String url = "/public/v1.0/security/access_token/sf_appid/" + appInfo.setAppId + "/ sf_appkey/" + appInfo.setAppKey;
            //MessageResp<TokenRespDto> apply = SecurityTools.applyAccessToken(applyUrl, appInfo);
            MessageReq<LinPaiReqDto> req = new MessageReq<LinPaiReqDto>();
            HeadMessageReq reqHQ = new HeadMessageReq
            {
                transType = "301",
                transMessageId = "11111111111222"
            };
            req.head = reqHQ;
            LinPaiReqDto linPaiHQ = new LinPaiReqDto
            {

            };
            req.body = linPaiHQ;
            MessageResp<LinPaiRespDto> respHQ = new MessageResp<LinPaiRespDto>();
            try
            {
                var httpClient = sfkd.GetClient();
                var responseMsg = httpClient.PostAsJsonAsync(url, req).Result;
                responseMsg.EnsureSuccessStatusCode();
                respHQ = responseMsg.Content.ReadAsAsync<MessageResp<LinPaiRespDto>>().Result;
                //response = responseMsg.Content.ReadAsAsync<MessageResp<OrderReqDto>>().Result;
            }
            catch (Exception ex)
            {
                //Logger.ErrorFormat("调用院内获取病人信息Api出错,信息：{0}", JsonConvert.SerializeObject(ex));
                //return new AddBindingResponse
                //{
                //    ResultCode = "3",
                //    ResultMsg = "操作失败，获取就诊卡信息超时"
                //};
            }
            if (respHQ.head.code != "EX_CODE_OPENAPI_0200")
            {
                respQuery.head.message = respHQ.head.code;
                return respQuery;
            }

            string urlFilter = "/rest/v1.0/order/query/access_token/" + respHQ.body.accessToken + "/ sf_appid /" + appInfo.setAppId + "/ sf_appkey/" + appInfo.setAppKey;
            MessageReq<OrderQueryReqDto> reqQuery = new MessageReq<OrderQueryReqDto>();
            HeadMessageReq reqXD = new HeadMessageReq
            {
                transType = "203",
                transMessageId = "111111145624223588"
            };
            reqQuery.head = reqXD;
            OrderQueryReqDto dtoXD = new OrderQueryReqDto
            {
               orderId= "4vhU2plNE0WFGy4zZbvzJ694"
            };
            reqQuery.body = dtoXD;
            try
            {
                var httpClient = sfkd.GetClient();
                var responseMsg = httpClient.PostAsJsonAsync(urlFilter, reqQuery).Result;
                responseMsg.EnsureSuccessStatusCode();
                respQuery = responseMsg.Content.ReadAsAsync<MessageResp<OrderQueryRespDto>>().Result;
                //response = responseMsg.Content.ReadAsAsync<MessageResp<OrderReqDto>>().Result;
            }
            catch (Exception ex)
            {
                //Logger.ErrorFormat("调用院内获取病人信息Api出错,信息：{0}", JsonConvert.SerializeObject(ex));
                //return new AddBindingResponse
                //{
                //    ResultCode = "3",
                //    ResultMsg = "操作失败，获取就诊卡信息超时"
                //};
            }
            if (respQuery.head.code != "EX_CODE_OPENAPI_0200" && respQuery.head.message == "操作成功")
            {
                return respQuery;
            }

            return respQuery;
        }

        /// <summary>
        /// 路由查询
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [ActionName("testRouteQuery")]
        [AllowAnonymous]
        public testRouteQuery testRouteQuery(string orderId)
        {

            var azUser = AzUser.GetInApi(Request);
            var card = _ctx.Addresses.FirstOrDefault(x => x.IsDefault == 1 && x.WxUserId == azUser.UserId);
            
            if (card == null)
            {
                return new testRouteQuery
                {
                    ResultCode = "1",
                    ResultMsg = "找不到就诊卡信息"
                };
            }

            MessageResp<List<RouteQueryRespDto>> response = new MessageResp<List<RouteQueryRespDto>>();
            MessageResp<LinPaiRespDto> linPaiResp = linPai();
            var newSFOrderNo = SFKDNewOrderNo();
            if (linPaiResp.body.accessToken == "")
            {
                return new testRouteQuery
                {
                    ResultCode = "1",
                    ResultMsg = "申请令牌出错"
                };
            }
            string urlFilter = "/rest/v1.0/route/query/access_token/" + linPaiResp.body.accessToken + "/sf_appid/" + setAppId + "/sf_appkey/" + setAppKey;

            MessageReq<RouteQueryReqDto> reqQuery = new MessageReq<RouteQueryReqDto>();
            HeadMessageReq reqXD = new HeadMessageReq
            {
                transType = "501",
                transMessageId = newSFOrderNo
            };
            reqQuery.head = reqXD;
            RouteQueryReqDto dtoXD = new RouteQueryReqDto()
            {
                methodType = 1,
                trackingNumber = orderId,
                trackingType = 2
            };
            reqQuery.body = dtoXD;
            try
            {
                var httpClient = sfkd.GetClient();
                var responseMsg = httpClient.PostAsJsonAsync(urlFilter, reqQuery).Result;
                responseMsg.EnsureSuccessStatusCode();
                response = responseMsg.Content.ReadAsAsync<MessageResp<List<RouteQueryRespDto>>>().Result;
                //response = responseMsg.Content.ReadAsAsync<MessageResp<OrderReqDto>>().Result;
            }
            catch (Exception ex)
            {
                //Logger.ErrorFormat("调用院内获取病人信息Api出错,信息：{0}", JsonConvert.SerializeObject(ex));
                //return new AddBindingResponse
                //{
                //    ResultCode = "3",
                //    ResultMsg = "操作失败，获取就诊卡信息超时"
                //};
            }

            if (response.head.code == "EX_CODE_OPENAPI_0105" || response.head.code == "EX_CODE_OPENAPI_0106")
            {
                MessageResp<LinPaiRespDto> newLinPaiResp = newLinPai();
                testRouteQuery newOrder = testRouteQuery(orderId);
                return newOrder;
            }
            if (response.head.code != "EX_CODE_OPENAPI_0200")
            {
                return new testRouteQuery
                {
                    ResultCode = "1",
                    ResultMsg = linPaiResp.head.message
                };
            }
            var dto = new List<testRouteQuery.RouteQuery>();
            foreach (var bodys in response.body)
            {
                dto.Add(new testRouteQuery.RouteQuery
                {
                    acceptAddress = bodys.acceptAddress,
                    acceptTime = bodys.acceptTime,
                    mailNo = bodys.mailNo,
                    opcode = bodys.opcode,
                    orderId = bodys.orderId,
                    remark = bodys.remark
                });
            }

            return new testRouteQuery
            {
                ResultCode = "0",
                //ResultMsg = linPaiResp.head.message,
                RouteQuerys = dto
            };
        }

        /// <summary>
        /// 电子运单图片下载
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [ActionName("testWaybillImage")]
        [AllowAnonymous]
        public MessageResp<WaybillRespDto> testWaybillImage()
        {
            MessageResp<WaybillRespDto> respQuery = new MessageResp<WaybillRespDto>();
            AppInfo appInfo = new AppInfo();
            appInfo.setAppId = ("00023655");
            appInfo.setAppKey = ("129A43A3C58088458A88D208384DED36");
            String url = "/public/v1.0/security/access_token/sf_appid/" + appInfo.setAppId + "/ sf_appkey/" + appInfo.setAppKey;
            //MessageResp<TokenRespDto> apply = SecurityTools.applyAccessToken(applyUrl, appInfo);
            MessageReq<LinPaiReqDto> req = new MessageReq<LinPaiReqDto>();
            HeadMessageReq reqHQ = new HeadMessageReq
            {
                transType = "301",
                transMessageId = "11111111111222"
            };
            req.head = reqHQ;
            LinPaiReqDto linPaiHQ = new LinPaiReqDto
            {

            };
            req.body = linPaiHQ;
            MessageResp<LinPaiRespDto> respHQ = new MessageResp<LinPaiRespDto>();
            try
            {
                var httpClient = sfkd.GetClient();
                var responseMsg = httpClient.PostAsJsonAsync(url, req).Result;
                responseMsg.EnsureSuccessStatusCode();
                respHQ = responseMsg.Content.ReadAsAsync<MessageResp<LinPaiRespDto>>().Result;
                //response = responseMsg.Content.ReadAsAsync<MessageResp<OrderReqDto>>().Result;
            }
            catch (Exception ex)
            {
                //Logger.ErrorFormat("调用院内获取病人信息Api出错,信息：{0}", JsonConvert.SerializeObject(ex));
                //return new AddBindingResponse
                //{
                //    ResultCode = "3",
                //    ResultMsg = "操作失败，获取就诊卡信息超时"
                //};
            }
            if (respHQ.head.code != "EX_CODE_OPENAPI_0200")
            {
                respQuery.head.message = respHQ.head.code;
                return respQuery;
            }

            string urlFilter = "/rest/v1.0/waybill/image/access_token/" + respHQ.body.accessToken + "/ sf_appid /" + appInfo.setAppId + "/ sf_appkey/" + appInfo.setAppKey;
            MessageReq<WaybillReqDto> reqQuery = new MessageReq<WaybillReqDto>();
            HeadMessageReq reqXD = new HeadMessageReq
            {
                transType = "205",
                transMessageId = "170218235756000005"
            };
            reqQuery.head = reqXD;
            WaybillReqDto dtoXD = new WaybillReqDto()
            {
                orderId= "4vhU2plNE0WFGy4zZbvzJ684"
            };
            reqQuery.body = dtoXD;
            try
            {
                var httpClient = sfkd.GetClient();
                var responseMsg = httpClient.PostAsJsonAsync(urlFilter, reqQuery).Result;
                responseMsg.EnsureSuccessStatusCode();
                respQuery = responseMsg.Content.ReadAsAsync<MessageResp<WaybillRespDto>>().Result;
                //response = responseMsg.Content.ReadAsAsync<MessageResp<OrderReqDto>>().Result;
            }
            catch (Exception ex)
            {
                //Logger.ErrorFormat("调用院内获取病人信息Api出错,信息：{0}", JsonConvert.SerializeObject(ex));
                //return new AddBindingResponse
                //{
                //    ResultCode = "3",
                //    ResultMsg = "操作失败，获取就诊卡信息超时"
                //};
            }
            if (respQuery.head.code != "EX_CODE_OPENAPI_0200" && respQuery.head.message == "操作成功")
            {
                return respQuery;
            }

            return respQuery;
        }

        /// <summary>
        /// 生成快递订单号
        /// </summary>
        /// <returns></returns>
        public static string GenerateNewOrderNo()
        {
            var orderNo = "SFKD" + DateTime.Now.Date.ToString("yyyyMMdd");
            lock (OrderNoLocker)
            {
                orderNo += (DateTime.Now - DateTime.Now.Date).TotalMilliseconds.ToString("00000");
                Thread.Sleep(1);
            }

            return orderNo;
        }

        /// <summary>
        /// 获取所有顺丰快递
        /// </summary>
        /// <param name="type">current - 15内订单 history - 历史订单</param>
        /// <returns></returns>
        [HttpGet]
        [ActionName("GetOrderList")]
        public GetOrderListResponse GetOrderList(string type = "current")
        {
            var azUser = AzUser.GetInApi(Request);
            List<GetOrderListResponse.Order> orders;

            if (type == "current")
            {
                //orders =
                //    _ctx.BillOrders.Where(x => x.WxUserId == azUser.UserId).IsStatus(BillOrderExtensions.OrderStatus.缴费成功)
                //        .Where(x => SqlFunctions.DateDiff("day", x.CreateTime, DateTime.Today) <= 15)
                //        .OrderByDescending(x => x.OrderDate).ThenByDescending(x => x.CreateTime).ToList();
                using (var ctx = new GdsfybjyWeiXinEntities())
                {
                    MySqlParameter[] para =
                    {
                        new MySqlParameter("@UserId", azUser.UserId),
                        new MySqlParameter("@Today", DateTime.Today)
                };
                    orders = ctx.Database.SqlQuery<GetOrderListResponse.Order>(
                        "select OrderId,CardName,Address,ClinicNo,OrderNo,CreateTime from SFKDorder where OrderStatus = 1 and WxUserId = @UserId and datediff(@Today,CreateTime)<=15  ",
                        para).ToList();
                }
            }
            else
            {
                //orders =
                //    _ctx.BillOrders.Where(x => x.WxUserId == azUser.UserId).IsStatus(BillOrderExtensions.OrderStatus.缴费成功)
                //        .Where(x => SqlFunctions.DateDiff("day", x.CreateTime, DateTime.Today) > 15)
                //        .OrderByDescending(x => x.OrderDate).ThenByDescending(x => x.CreateTime).ToList();
                using (var ctx = new GdsfybjyWeiXinEntities())
                {
                    MySqlParameter[] para =
                    {
                        new MySqlParameter("@UserId", azUser.UserId),
                        new MySqlParameter("@Today", DateTime.Today)
                };
                    orders = ctx.Database.SqlQuery<GetOrderListResponse.Order>(
                        "select OrderId,CardName,Address,ClinicNo,ClinicNo,OrderNo from SFKDorder where OrderStatus = 1 and WxUserId = @UserId and datediff(@Today,CreateTime)>=15  ",
                        para).ToList();
                }
            }

            return new GetOrderListResponse
            {
                ResultCode = "0",
                ResultMsg = "",
                Orders = orders
            };
        }
        /// <summary>
        /// 顺丰交易流水号
        /// </summary>
        /// <returns></returns>
        public static string SFKDNewOrderNo()
        {
            var orderNo = DateTime.Now.Date.ToString("yyyyMMdd");
            lock (OrderNoLocker)
            {
                orderNo += (DateTime.Now - DateTime.Now.Date).TotalMilliseconds.ToString("0000000000");
                Thread.Sleep(1);
            }

            return orderNo;
        }
    }
}